﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.Localization;
using Orchard.Logging;
using Rework.SocialMetadata.Models;
using Rework.SocialMetadata.Settings;
using Rework.SocialMetadata.ViewModels;

namespace Rework.SocialMetadata.Services {
    public class SocialMetadataServices : ISocialMetadataServices {
        private readonly IContentDefinitionManager _contentDefinitionManager;

        public SocialMetadataServices(IContentDefinitionManager contentDefinitionManager) {
            _contentDefinitionManager = contentDefinitionManager;

            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
        }

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }
        
        public SocialMetadataEditViewModel BuildSocialMetadataEditViewModel(SocialMetadataPart part) {
            SocialMetadataEditViewModel viewModel = new SocialMetadataEditViewModel();
            viewModel.Pattern = part.Pattern;
            viewModel.UsePattern = part.UsePattern;
            return viewModel;
        }
                
        public void UpdateSocialMetadataPart(ref SocialMetadataPart part, SocialMetadataEditViewModel viewModel) {
            part.Pattern = viewModel.Pattern;
            part.UsePattern = viewModel.UsePattern;
        }

        public string GetContentTypePattern(string contentType) {
            var settings = GetTypePartSettings(contentType).GetModel<SocialMetadataTypePartSettings>();
            return settings.Pattern;
        }

        private SettingsDictionary GetTypePartSettings(string contentType) {
            var contentDefinition = _contentDefinitionManager.GetTypeDefinition(contentType);

            if (contentDefinition == null) {
                throw new OrchardException(T("Unknown content type: {0}", contentType));
            }

            return contentDefinition.Parts.First(x => x.PartDefinition.Name == "SocialMetadataPart").Settings;
        }
    }
}